<template>
<div class="roleMng components-container">
	<!--=========头部=========-->
	<div class="searchBar">
	<fns-header @search="queryList">
      <span slot="slot1" class="slot">
          <el-form-item label="角色名称">
              <el-input v-model="header.name" placeholder="请输入角色名称" :maxlength="30" @keyup.enter.native="queryList" clearable></el-input>
          </el-form-item>
          <el-form-item label="状态">
              <el-select v-model="header.status" placeholder="请选择状态" clearable>
						    <el-option
						      v-for="item in stateOption"
						      :key="item.value"
						      :label="item.label"
						      :value="item.value">
						    </el-option>
						  </el-select>
          </el-form-item>
      </span>
	</fns-header>
	</div>
	<!--=======表格=======-->
	<div class="fns-table-handle mainTable">
	  <div class="btnLine">
		<el-button type="primary" size="medium" icon="iconfont icon-xinzeng" @click="updateAndAdd('', 'add')" v-has="'pcadmin_sys_sys_role_create'"> 新增</el-button>
	  </div>
	<fns-table :customerField="customerField">
		 <el-table-column
			slot="right"
      prop="userCount"
      label="用户数"
      align="left"
      width="150"
      >
      <template slot-scope="scope">
      <a v-if="scope.row.userCount!==0" style="color:#409EFF" @click="handleCount(scope)">{{scope.row.userCount}}</a>
       <span v-else style="color:#808080">{{scope.row.userCount}}</span>
      </template>
    </el-table-column>
    <el-table-column
				slot="right"
      prop="createdOn"
      label="创建时间"
      align="left"
      >
    </el-table-column>
    <el-table-column
				slot="right"
      prop="status"
      label="状态"
      align="left"
      :formatter="formatterStatus"
      >
    </el-table-column>
	  <el-table-column
				slot="right"
				label="操作"
				align="center"
				fixed="right"
				width="180">
		  <template slot-scope="scope">
			<el-tooltip content="查看" placement="top"  v-has="'pcadmin_sys_sys_role_detail'">
			  <el-button type="mini" icon="iconfont icon-chakan3" @click="updateAndAdd(scope, 'detail')"></el-button>
			</el-tooltip>
			<el-tooltip content="修改" placement="top"  v-has="'pcadmin_sys_sys_role_update'">
			   <el-button type="mini" icon="iconfont icon-xiugai"  @click="updateAndAdd(scope, 'update')"></el-button>
			</el-tooltip>
			<el-tooltip content="权限分配" placement="top"  v-has="'pcadmin_sys_sys_role_assign_permissions'">
			 <el-button type="mini" icon="iconfont icon-fenpei1" @click="permissionAssign(scope)"></el-button>
			</el-tooltip>
			<el-tooltip content="删除" placement="top" v-has="'pcadmin_sys_sys_role_delete'" >
			  <el-button type="mini" icon="iconfont icon-shanchu-" @click="openModel(scope, 'delete')" :disabled="scope.row.userCount!==0"></el-button>
			</el-tooltip>
		  </template>
		</el-table-column>
	</fns-table>

	<!-- ========页码======-->
	<pages v-on:_pageChange="_pageChange" :total="total" :currentPage="page.index"></pages>

	</div>
	<!--重置/删除/停用弹窗-->
	<fns-dialog :dialogData="moreData" @submitForm="submitForm" width="100%" class="fns-model-center">
	  <div slot="body" style="margin-top: 5px;text-align: center;margin-bottom: -5px;">
		<span class="iconfont icon-wenhao" style="color: red;"></span>
		<span v-if = 'moreData.title === "删除"'>你确定要删除此角色吗？</span>
		<span v-if = 'moreData.title === "停用"'>你确定要停用此角色吗？？</span>
	  </div>
	</fns-dialog>
	<div v-if="dialogData.dialogVisible">
	<fns-dialog :dialogData="dialogData" @submitForm="submitForm" width="100%" >
  	<el-form  class="addRoleMng" id='roleModel' ref="roleModel" :model="roleModel" :rules="rules" label-width="100px"  slot="body" v-loading="loading2">

 			<el-row class="roleInfo">
 				<el-form-item label="角色名称" :prop="isValidate ? 'displayName': ''">
 				  <el-input v-model="roleModel.displayName" type="text" placeholder="请输入角色名称" :disabled="isValidate ? false : true" :maxlength="20" :clearable="isValidate ? true : false"></el-input>
 				</el-form-item>
 			</el-row>

 			<el-row>
 				<el-form-item  label="状态"  :prop="isValidate ? 'status': ''">
 					<template>
             <el-radio-group v-model="roleModel.status" :disabled="isValidate ? false : true">
                <el-radio v-for="(status, index) in stateOption" :label="status.value" :key="index" >{{status.label}}</el-radio>
             </el-radio-group>
           </template>
 				</el-form-item>
 			</el-row>

 	    <el-row>
 				<el-form-item class="wid-md" label="角色描述" prop="remark">
 				  <el-input v-model="roleModel.remark" type="textarea" :rows="2" resize="none"  :placeholder="isValidate ? '请输入您的描述' : ''" :disabled="isValidate ? false : true" :maxlength="200":clearable="isValidate ? true : false"></el-input>
				</el-form-item>
 		  </el-row>

  	</el-form>
	</fns-dialog>
</div>
	<!--用户数弹窗-->
	<div v-if="userDialog.dialogVisible">
	<fns-dialog :dialogData="userDialog" width="100%">
		 <div slot="body" >
		 	<fns-table :customerField="userField"></fns-table>
		 	 <!-- ========页码======-->
			<pages v-on:_pageChange="_userPageChange" :total="pagination.total" :pageSizes="pagination.pageSizes"  :currentPage="userPage.index" :pageSize="pagination.pageSize"></pages>
		 </div>
	</fns-dialog>
</div>
	<!-- 权限分配弹窗 -->
	<div v-if="permissionDialog.dialogVisible">
	<fns-dialog :dialogData="permissionDialog" @submitForm="submitPermission" width="100%" class="authDialog">
		
		 <el-form label-width="100px"  slot="body">
			<el-row  class="roleInfo">
					<el-col :span="24">
						<el-form-item class="treeWrapper">
							<el-tree
							v-loading="loading"
					      :data="authObj"
					      ref="tree"
					      show-checkbox
					      auto-expand-parent
					      :default-expanded-keys="treeModel.expandedKeys"
					      :default-checked-keys="treeModel.checkedKeys"
					      node-key="id"
					      :props="defaultProps"
					      v-model="treeModel.resourceIds"
					      @check="checkedAuth">
					    </el-tree>
			  	</el-form-item>
			   </el-col>
			</el-row>
		</el-form></fns-dialog></div>
</div>
</template>
<script>
import { formaterTableData, initScrollTop, clearForm } from '@/utils/publicMethod'
import * as api from '@/api/system/roleMng'
import pages from '@/components/common/page' // 分页
import fnsHeader from '@/components/common/header' // 头部
import fnsDialog from '@/components/common/dialog' // 弹窗
import fnsLookImg from '@/components/common/lookImg' // 查看图片
import fnsTable from '@/components/common/table' // 表格
import fnsUpload from '@/components/common/upload' // 上传图片
import * as validate from '@/utils/validate' // 验证
import { mapState } from 'vuex'
export default {
	name: 'Role',
	data() {
		return {
			authObj: [],
			defaultProps: {
        children: 'children',
        label: (data, node) => {
        	return data.data.name
        }
      },
      loading: false,
      loading2: false,
      treeModel: {
      	resourceIds: '',
				expandedKeys: [],
				checkedKeys: [],
      },
			dialogData: { // 中号弹窗
			  title: '',
			  dialogVisible: false,
			   showBackBtn: false,
			  size: 'md', // lg, md , sm
			  btnLeft: '取 消',
			  btnRight: '提 交'
			},
			moreData: {
			  title: '',
			  dialogVisible: false,
			  size: 'sm',
			  btnLeft: '取 消',
			  btnRight: '确 定'
			},
			userDialog: {
				title: '用户列表',
				dialogVisible: false,
				showBackBtn: true,
				size: 'md'
			},
			permissionDialog: {
				title: '权限分配',
				dialogVisible: false,
				size: 'md',
				btnLeft: '取 消',
				btnRight: '提 交'
			},
			roleId: '',
			roleModel: {
			  displayName: '',
			  status: 1,
			  remark: ''
			},
			rules: {
			  displayName: [
				validate.blur(),
				validate.noSpace
			  ],
			  status: [
				validate.blur()
			  ]
			},
			header: {
				name: '',
				status: ''
			},
			page: {
				index: 1,
				size: 10
			},
			total: 0,
			userPage: {
				index: 1,
				size: 5
			},
			pagination: {
				total: 0,
				pageSizes: [5, 10, 15, 20],
				pageSize: 5
			},
			customerField: { // 自定义表格字段
			  tableData: [],
			  loading: false,
			  border: true,
			  allField: [
				{
				  prop: 'id',
				  label: '序号',
				  type: 'index',
				  align: 'left',
				  width: '80'
				},
				{
				  prop: 'name',
				  label: '角色名称',
				  align: 'left'
				}
			  ]
			},
			userField: {
				tableData: [],
			  loading: false,
			  border: true,
			  allField: [
			  {
				  prop: 'id',
				  label: '序号',
				  type: 'index',
				  align: 'center'
				},
				{
				  prop: 'userName',
				  label: '用户名',
				  align: 'center'
				},
				{
				  prop: 'realName',
				  label: '姓名',
				  align: 'center'
				},
				{
				  prop: 'phoneNum',
				  label: '手机号',
				  align: 'center'
				},
			  ]
			},
			isValidate: false
		}
	},
	computed: {
	  ...mapState({
		stateOption: state => state.selected.state
	  })
	},
	created() {
		// this.queryList()
	},
	mounted() {
		this.queryList()
	},
	watch: {
	  ['dialogData.dialogVisible'] (val) {
      if (!val) {
			  if (this.$refs['roleModel'] !== undefined) { // 重置表单及移除验证
					this.$refs['roleModel'].resetFields()
			  }
			}
	  }
	},
	methods: {
	  permissionAssign(scope) {  // 权限分配
	  	// 初始化树型权限
			this.getResourceList().then(res => {
				this.permissionDialog.dialogVisible = true
		  	this.roleId = scope.row.id
		  	this.getRoleResource()   // 获取当前角色的所有权限，赋值于树型
			})    	
	  },
		getResourceList() {
			return new Promise((resolve, reject) => {
				this.loading = true
				this.authObj = []
	  		api.resourceList().then(res => {
	  			if (res.data !== null&&res.data.children !== null) {
		  			this.authObj = res.data.children
		  		}
		  		this.loading = false
		  		resolve(res)
		  	})
			})
	  },
	  getRoleResource() {
	  	this.loading = true
	  	api.roleResourceList(this.roleId).then((res) => {
	  		/*let roleIds = []
	  		res.data.forEach(item => {
					roleIds.push(item.extData.id)
	  		})*/
	  		this.$nextTick(() => {
		  		this.$refs.tree.setCheckedKeys(res.data)
		  		if (res.data.length !== 0) {
		  			this.treeModel.expandedKeys = res.data
		  		} else {
		  			this.treeModel.expandedKeys = ['5','37']
		  		}
		  		this.treeModel.resourceIds = res.data
		  		this.loading = false
		  	})
	  	})
	  },
		checkedAuth(obj, checkedObj) {  // 勾选权限
			this.treeModel.resourceIds = checkedObj.checkedKeys  // 当前勾选的所有权限
		},
		submitPermission() {
			api.addPermission(this.roleId, this.treeModel.resourceIds).then((res) => {
				this.permissionDialog.dialogVisible = false
			})
		},
		_pageChange(val, flag) {
			let arr = []
			if (flag === 'size') {
			  this.page.index = val
			  this.queryList()
			} else {
			  arr.push(val)
			  this.page.index = 1
			  this.page.size = arr[0]
			  this.queryList()
			}
	  },
	  _userPageChange(val, flag) {
	  	let arr = []
			if (flag === 'size') {
			  this.userPage.index = val
			  this.queryUserList(this.roleId)
			} else {
			  arr.push(val)
			  this.userPage.index = 1
			  this.userPage.size = arr[0]
			  this.queryUserList(this.roleId)
			}
	  },
		search() {
			this.page.index = 1
			this.queryList()
	  },
	  queryList() {
			this.customerField.loading = true
			let pages = {
			  index: this.page.index,
			  size: this.page.size
			}
			let data = Object.assign({}, this.header, pages)
			api.roleList(data).then((res) => {
			  // this.tableData = formaterTableData(res.data.rows) // 格式化表格数据
			  this.customerField.tableData = res.data.rows
			  this.total = +res.data.total
			  this.customerField.tableData.map((item, index) => {
				for (var i in item) {
				  if (item[i] === null || '') {
					item[i] = ' '
				  }
				}
			  })
			  this.customerField.loading = false
			}).catch(() => {
			  this.customerField.loading = false
			})
	  },
	  queryUserList(roleId) {
	  	this.userField.loading = true
			let pages = {
			  index: this.userPage.index,
			  size: this.userPage.size
			}
			let data = Object.assign({}, {roleId: roleId}, pages)
			api.userList(data).then((res) => {
			  // this.tableData = formaterTableData(res.data.rows) // 格式化表格数据
			  this.userField.tableData = res.data.rows
			  this.pagination.total = +res.data.total
			  this.userField.tableData.map((item, index) => {
				for (var i in item) {
				  if (item[i] === null || '') {
					item[i] = ' '
				  }
				}
			  })
				this.pagination.currentPage = 1
			  this.userField.loading = false
			}).catch(() => {
			  this.userField.loading = false
			})
	  },
	  updateAndAdd(res, name) {
			this.dialogData.title =  name === 'add' ? '新增角色' :  name === 'update' ? '修改角色' : name === 'detail' ? '查看角色' : ''
			this.dialogData.dialogVisible = true
			this.roleId = res ? res.row.id : ''
			clearForm(this.roleModel)
			/*if (this.$refs['roleModel'] !== undefined) { // 重置表单及移除验证
			  	this.$refs['roleModel'].clearValidate()
				}*/
			if (name === 'add') {
				this.roleModel.status = 1
				this.isValidate = true
				this.dialogData.showBackBtn = false
			} else if (name === 'update') {
				this.isValidate = true
				this.dialogData.showBackBtn = false
				this.roleDetail() // 回显
			} else {
				this.isValidate = false
				this.dialogData.showBackBtn = true
				this.roleDetail() // 回显
			}
	  },
	  // 打开删除、重置密码、停用弹窗
	  openModel(res, name) {
		this.moreData.dialogVisible = true
		this.moreData.title =  name === 'delete' ? '删除' :  name === 'reset' ? '重置' : name === 'stop' ? '停用' : ''
		this.roleId = res ? res.row.id : ''
	  },
	  submitForm(val) {
	  	if (val === '新增角色') {
				this.$refs['roleModel'].validate((valid) => {
				  if (valid) {
						this.addRole()
				  }
				})
			} else if (val === '修改角色'){
				this.$refs['roleModel'].validate((valid) => {
				  if (valid) {
						this.updateRole()
				  }
				})
			} else if (val === '删除'){
				this.deleteRole()
			} else {
				return
			}
		},
		handleCount(scope) {
			this.pagination.pageSize = 5
			this.userPage.index = 1
			this.userPage.size =5
			this.roleId = scope.row.id
			this.userDialog.dialogVisible = true
			this.queryUserList(this.roleId)
		},
		addRole() {
			api.addRole(this.roleModel).then((res) => {
				if(+res.code === 0) {
					this.dialogData.dialogVisible = false
				  this.page.index = 1
					this.queryList()
				}
			})
		},
		updateRole() {
			api.updateRole(this.roleId, this.roleModel).then((res) => {
				if(+res.code === 0) {
					this.dialogData.dialogVisible = false
					this.queryList()
				}
			})
		},
		deleteRole() {
			api.deleteRole(this.roleId).then((res) => {
				if(+res.code === 0) {
					this.moreData.dialogVisible = false
					this.queryList()
				}
			})
		},
		roleDetail() {
			this.loading2 = true
			api.roleDetail(this.roleId).then((res) => {
				if(+res.code === 0) {
					var rowData = res.data
					// this.roleModel = { ...res.data }
					// this.roleModel.id = rowData.id || ''
					this.roleModel.displayName = rowData.displayName || ''
					this.roleModel.remark = rowData.remark || ''
					this.roleModel.status = Number(rowData.status || 0)
				/*	if (this.$refs['roleModel'] !== undefined) { // 重置表单及移除验证
					  this.$refs['roleModel'].resetFields()
					}*/
				}
				this.loading2 = false
			})
		},
	  formatterStatus(row) {
			var value = row.status || ''
			var el = ''
			if (value === 1) {
				el = '启用'
			} else {
				el = '停用'
			}
			return el
	  }
	},
	components: {
	  pages,
	  fnsHeader,
	  fnsTable,
	  fnsDialog,
	  fnsLookImg,
	  fnsUpload
	}
}
</script>
<style lang="scss">
  .roleMng {
    .addRoleMng {
    	margin-top: 20px;
  	// .roleInfo {
  	// 	padding-left: 25px !important;
  	// 	.el-input {
  	// 		width: 50% !important;
  	// 	}
  	// }
	  	.treeWrapper {
	  		border: 1px solid #D9D9D9;
	  		background-color: #FFF;
	  		height: 210px;
	  		overflow: auto;
	  		width: 100% !important;
	  		.el-form-item__content {
	  			margin-left: 0 !important;
	  		}
	  	}
	  	.titleWrapper {
	  		border-left: 3px solid #5299FF;
	  		padding-left: 5px;
	  		margin-bottom: 29px;
	  		.title {
	  			font-size: 16px;
	  		}
	  	}
	  	.fns-table-handle {
				margin-top: 20px;
	  	}
  	}
  	.authDialog {
  		.el-form {
  			height: 320px !important;
  			.treeWrapper {
			width: 100% !important;
  			}
  			.el-form-item__content {
  				margin-right: 72px !important;
  				width: 80% !important;
  			}
  		}
  	}
  }
</style>